<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton
  // ElTag,
  // ElMessageBox
} from 'element-plus'

import { Table } from '@/components/Table'

import { adminFaPastureListApi, adminFaPastureEditApi } from '@/api/fa/pasture'
import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import Add from './components/Add.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
import { ElMessage, ElMessageBox } from 'element-plus'
// 获取字典
// import { useCache } from '@/hooks/web/useCache'
// const { wsCache } = useCache()
// const dict: any = wsCache.get('dict')
// 字典通过value获取label
// const getDictLabel = (type, value) => {
//   let data = dict[type].find((item) => {
//     return item.value == value
//   })
//   return data ? data.label : ''
// }

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDelete = useIcon({ icon: 'material-symbols:delete-outline' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: adminFaPastureListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'code',
    label: '客户',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'name',
    label: '所属牧场',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'creation_user_name',
    label: '类型',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'address',
    label: '出库类型',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'legal_name',
    label: '入库类型',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'creation_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'operator_name',
    label: '备注',
    width: 150,
    search: {
      show: false
    }
  },
  // {
  //   field: 'update_user_name',
  //   label: '创建人',
  //   width: 80,
  //   form: {
  //     show: false
  //   }
  // },
  {
    field: 'action',
    width: 150,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      // tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          // console.log(3333, data, adminFaPastureEditApi)
          let res = await adminFaPastureEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'add':
      console.log('aaa')
      if (addSons.value[0]) {
        // const aaa = { ...addSons.value[0], ...addSons.value[1] }
        addSons.value[0].creation_time = timestampToTime(
          new Date(addSons.value[0].creation_time).getTime()
        )
        console.log(addSons.value[0])
        dialogVisible.value = false
      } else {
        alert('aaaaa,没填完')
        console.log(addSons.value[0])
      }

      break
    default:
      console.log('未知类型')
  }
}

// 删除提示
const DDelete = (row) => {
  ElMessageBox.confirm('确定删除吗', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消'
      })
    })
  console.log(row)
}
const addSons = ref()
function timestampToTime(timestamp) {
  if (timestamp === 0 || timestamp == null) {
    return ''
  } else {
    var date = new Date(timestamp)
    var Y = date.getFullYear() + '-'
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    return Y + M + D
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="true"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="修改" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton circle :icon="iconDelete" @click="DDelete(row)" title="删除" />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add
      v-if="actionType == 'edit'"
      ref="editRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <Add
      v-if="actionType == 'add'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      ref="addSons"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
